package application;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import util.PropertyUtil;
import util.RegisterUtil;

public class RegisterForm extends AnchorPane implements Initializable { 
	    @FXML  
	    TextField codeField; 
	    @FXML
	    Button cancelButton;
	    @FXML
	    Button okButton;
	    @FXML
	    TextField actionText;
	    @FXML
	    Text alert;
	      
	    private static RegisterForm registerForm;  
	    private static Stage newAlertDialog ;  
	      
	    RegisterForm() {
	    	
	        FXMLLoader fXMLLoader = new FXMLLoader
	        		(getClass().getClassLoader().getResource("view/Register.fxml"));  
	        fXMLLoader.setRoot(RegisterForm.this);  
	        fXMLLoader.setController(RegisterForm.this);
	        try {  
	            fXMLLoader.load();  
	        } catch (IOException exception) {  
	            throw new RuntimeException(exception);  
	        }  
	    }  
	      
	    public static void showAlertDialog() {  
	        newAlertDialog = new Stage();  
	        newAlertDialog.setResizable(false);  
	        registerForm = new RegisterForm();  
	        newAlertDialog.setScene(new Scene(registerForm));
	        newAlertDialog.setTitle("提示");
	        newAlertDialog.getIcons().add(new Image("/images/icon.png"));
	        newAlertDialog.show();
			
	    }  
	      
	    public static void hideAlertDialog() {  
	        if(newAlertDialog != null) {  
	            newAlertDialog.hide();  
	        }  
	    }  
	  
	    @FXML  
	    private void onAlertOKClick(ActionEvent event) {  
	    	String code = codeField.getText();
	    	String reCode = RegisterUtil.getRegistrationCode();
	    	if(code.equals("")||code==null||code.length()!=8){
	    		alert.setText("请正确填写注册码！");
	    	}else if(!code.equals(reCode)){
	    		alert.setText("注册码不正确");
	    	}else{
	    		PropertyUtil.writeProperties("code", code);
	    		hideAlertDialog();
	    		Main main = new Main();
	    		main.start(new Stage());
	    	}
	    } 
	    
	    @FXML  
	    private void onAlertCancelClick(ActionEvent event) {  
	    	System.exit(0);  
	    }

		@Override
		public void initialize(URL location, ResourceBundle resources) {
			// TODO Auto-generated method stub
			actionText.setText(RegisterUtil.getLocalCode());
		}  
}  

